package com.smart.common.security;

import com.alibaba.fastjson.JSONObject;
import com.smart.common.smart.controller.JsonResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author arnold.zhao
 * @date 2018/10/17 17:47
 */
public class AuthenticationSuccessHandlerImpl extends SavedRequestAwareAuthenticationSuccessHandler {

    private String defaultSuccessUrl;

    /**
     * @Description: 用户验证成功后调用该方法，返回对应的json数据
     * @Param: [request, response, authentication]
     * @return: void
     * @Author: Arnold.zhao
     * @Date: 2018/10/17
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        String redirect = (String) request.getSession().getAttribute("requestURI");
        if (StringUtils.isBlank(redirect)) redirect = defaultSuccessUrl;

        //暂时不跳转登录前页面，默认走 defaultSuccessUrl
        redirect = defaultSuccessUrl;

        //对应的json输出
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain");

        JSONObject jsonObject = new JSONObject();

        PrintWriter out = response.getWriter();
        //校验对应的验证码是否输入正确
        String imageCode = request.getParameter("imageCode");
        if (StringUtils.isNotBlank(imageCode)) {
            if (!imageCode.equals(request.getSession().getAttribute("imageCode"))) {
                //表示验证码错误
                jsonObject.put("status", "-3");
                jsonObject.put("msg", "验证码错误,请重新输入");
            } else {
                jsonObject.put("status", "1");
                jsonObject.put("data", redirect);
                //验证码校验成功后，初始化对应用户数据initSession()
                initSession(request, response);
            }
        } else {
            //验证码不能为空
            jsonObject.put("status", "-4");
            jsonObject.put("msg", "验证码不能为空");
        }

        out.println(jsonObject.toString());
    }

    /**
     * @Description: 用于验证登录成功后，初始化对应的用户Session数据
     * @Param: [request, response]
     * @return: void
     * @Author: Arnold.zhao
     * @Date: 2018/10/17
     */
    public void initSession(HttpServletRequest request, HttpServletResponse response) {

    }

    public String getDefaultSuccessUrl() {
        return defaultSuccessUrl;
    }

    //用于注入对应的登录成功后跳转地址
    public void setDefaultSuccessUrl(String defaultSuccessUrl) {
        this.defaultSuccessUrl = defaultSuccessUrl;
    }
}
